import { PageContainer } from '@ant-design/pro-components';
import styles from './index.less';
import { useEffect, useState } from 'react';
import { Button, Popconfirm, Switch, Table, message, typeInputRef } from 'antd';
import type { TableColumnsType } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getCategoryList } from '@/services/ant-design-pro/good';
import {
  delCategory,
  getSingleCategoryInfo,
  modifyCategory,
} from '@/services/ant-design-pro/category';

import { Input } from 'antd';
import Modals from './Modals';

export interface DataType {
  key: React.Key;
  channelLogo: string;
  channelName: string;
  description: string;
  id: number;
  ordered: number;
  status: number;
  [property: string]: any;
}

const Goods = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [categoryList, setCategoryList] = useState([]);
  const [isAddChannelModalOpen, setIsAddChannelModalOpen] = useState(false);
  const [isChangeChannelModalOpen, setIsChangeChannelModalOpen] = useState(false);
  const [initialValues, setInitialValues] = useState();
  const [categoryStatuses, setCategoryStatuses] = useState({}); //管理每个分类的状态，显示或隐藏分类时需要用到

  const fetchGetCategoryList = async () => {
    const res = await getCategoryList();
    if (res.code === 0) {
      console.log('res.data', res.data);

      setCategoryList(res.data.sort((a, b) => a.ordered - b.ordered));
      // res.data.forEach(item => )
    } else {
      messageApi.error('分类列表获取失败');
    }
  };

  useEffect(() => {
    fetchGetCategoryList();
  }, []);

  const handleChangeChannel = async (goodsId: number) => {
    try {
      const res = await getSingleCategoryInfo(goodsId);
      if (res && res.code === 0) {
        setInitialValues(res.data);
        setIsChangeChannelModalOpen(true);
      } else {
        console.error('操作失败:', res.msg);
      }
    } catch (error) {
      console.error('请求失败:', error);
    }
  };

  const handleDelCategory = async (id: number) => {
    try {
      const res = await delCategory(id);
      if (res && res.code === 0) {
        messageApi.success('分类删除成功');
        fetchGetCategoryList();
      } else {
        messageApi.error(res.msg);
      }
    } catch (error) {
      console.log('删除分类的过程发生了错误', error);
    }
  };

  const handleChangeChannelStatus = async (record: any, checked: boolean) => {
    console.log(record, checked);
    try {
      const res = await modifyCategory({
        ...record,
        status: checked ? 0 : 1,
      });
      if (res.code === 0) {
        message.success(`分类已${checked ? '显示' : '隐藏'}`);
        fetchGetCategoryList();
      } else {
        message.error(res.msg);
        fetchGetCategoryList();
      }
    } catch (error) {
      console.error('分类显示修改发生错误', error);
    }
  };

  const columns: TableColumnsType<DataType> = [
    {
      title: 'logo',
      dataIndex: 'channelLogo',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <img className={styles.img} src={record.channelLogo} alt="" />
      ),
    },
    {
      title: '排序',
      dataIndex: 'ordered',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <Input disabled style={{ width: '50px' }} value={record.ordered} />
      ),
    },
    {
      title: '分类名称',
      dataIndex: 'channelName',
      align: 'center',
    },
    {
      title: '是否显示',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <>
          <Switch
            defaultChecked={record.status ? false : true}
            onChange={(checked) => handleChangeChannelStatus(record, checked)}
          />
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'x',
      key: 'x',
      width: '150px',
      fixed: 'right',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <div>
          <a style={{ marginRight: '20px' }} onClick={() => handleChangeChannel(record.id)}>
            修改
          </a>
          <Popconfirm
            title="确定要删除这个分类吗?"
            onConfirm={() => handleDelCategory(record.id)}
            okText="Yes"
            cancelText="No"
            placement="left"
          >
            <a className={styles.delBtn}>删除</a>
          </Popconfirm>
        </div>
      ),
    },
  ];

  return (
    <PageContainer>
      {contextHolder}
      <div className={styles.header}>
        <Button
          className={styles.addShop}
          icon={<PlusOutlined />}
          onClick={() => setIsAddChannelModalOpen(true)}
        >
          添加分类
        </Button>
      </div>
      <Table columns={columns} dataSource={categoryList} pagination={false} scroll={{ y: 500 }} />
      <Modals
        title="添加分类"
        isModalOpen={isAddChannelModalOpen}
        setIsModalOpen={setIsAddChannelModalOpen}
        fetchGetCategoryList={fetchGetCategoryList}
      />
      <Modals
        type={1}
        title="修改分类"
        isModalOpen={isChangeChannelModalOpen}
        setIsModalOpen={setIsChangeChannelModalOpen}
        initialValues={initialValues}
        fetchGetCategoryList={fetchGetCategoryList}
      />
    </PageContainer>
  );
};
export default Goods;
